package com.yuesystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuesystem.common.BaseContext;
import com.yuesystem.common.R;
import com.yuesystem.entity.Password;
import com.yuesystem.entity.User;
import com.yuesystem.service.PasswordService;
import com.yuesystem.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private PasswordService passwordService;

    /**
     * 用户登录
     *
     * @param request
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody Map map) {
        /**
         * 1.将页面提交的密码选行md5加密处理
         * 2、根据页面提交的手机号查询数据库
         * 3、如果没有查询到返回“账号或密码错误”
         * 4、密码比对，如果不一致则返回“账号或密码错误”
         * 5、登灵成功，将用户布入Session并返回登录成功结果
         */

        //1.将页面提交的密码选行md5加密处理
        String password = map.get("password").toString();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

//        2、根据页面提交的手机号查询数据库
//        3、如果没有查询到返回“账号或密码错误”
//        4、密码比对，如果不一致则返回“账号或密码错误”
        User one = userService.loginCheck(map.get("phone").toString(), password);

        if (one == null) {
            return R.error("账号或密码错误，请重试");
        }

//        5、登录成功，将用户布入Session并返回登录成功结果
        request.getSession().setAttribute("user", one);
        BaseContext.setCurrentId(one.getId());
        log.info("user已成功登录: {}", one);
        return R.success(one);
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        log.info("从session中取出的user为: {}", user);
        //清理session中用户保存的ID
        request.getSession().removeAttribute("user");
        if (user == null) {
            return R.error("该用户不存在");
        }
        return R.success("退出成功，欢迎下次再来！");
    }

    /**
     * 用户注册账号,注册后跳转到登录界面
     *
     * @param phone
     * @param code
     * @param password
     * @param confirmPassword
     * @return
     */
    @PostMapping("/register")
    public R<String> register(@RequestParam("phone") String phone, @RequestParam("code") String code,
                              @RequestParam("password") String password,
                              @RequestParam("confirmPassword") String confirmPassword, HttpSession session) {

        //两次输入的密码不匹配
        if (!password.equals(confirmPassword)) {
            log.info("两次输入的密码不一致，请重试！");
            return R.error("两次输入的密码不一致，请重试！");
        }

        //伪代码验证，设置验证码的值为1234
        session.setAttribute("code", "1234");

        //判断验证码是否正确
        Object codeInSession = session.getAttribute("code");
        if (!code.equals(codeInSession)) {
            log.info("验证码输入错误，请重试！");
            return R.error("验证码输入错误，请重试！");
        }

        //查询数据中是否有相同的手机号
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        queryWrapper.eq(User::getIsDeleted, 0);
        User one = userService.getOne(queryWrapper);

        if (one == null) {
            Password pw = new Password();
            pw.setPassword(password);

            User user = new User();
            user.setPhone(phone);
            user.setStatus(0);
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            user.setEncryptedPassword(password);
            userService.save(user);

            //获取刚注册用户的ID值,存入密码表
            LambdaQueryWrapper<User> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone)
                    .eq(User::getIsDeleted,0);
            Long userId = userService.getOne(queryWrapper).getId();
            pw.setUserId(userId);
            passwordService.save(pw);

            log.info("用户注册成功，user：{}", user);
            return R.success("注册成功，请重新登录");
        }
        log.info("该用户已存在，请重试！");
        return R.error("该用户已存在，请重试！");
    }




}
